﻿using LightCAD.Runtime;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LightCAD.UI
{
    public partial class DocumentControl : UserControl, IDocumentControl
    {
        MainUI mainUI;
        public DocumentControl()
        {
            InitializeComponent();

            this.Load += MainView_Load;
        }

        private void MainView_Load(object? sender, EventArgs e)
        {
            this.mainUI = this.Parent as MainUI;
            this.mainUI.ActiveChanged += MainUI_ActiveChanged;
            CommandCenter.Initilize(this.commandBar1);
        }

        private void MainUI_ActiveChanged(object? sender, MainUI.ActiveChangedEventArgs e)
        {
            if (e.IsActive)
            {
                CommandCenter.Instance.BindControl(this.commandBar1);
            }
            Debug.Print("DocumentControl IsActive: " + e.IsActive.ToString());
        }


        private void Instance_CommandExecute(object sender, CommandExecuteEventArgs e)
        {

        }
        internal int DrawingCount => this.drawings.Count;

        private List<DocumentRuntime> drawings = new List<DocumentRuntime>();
        internal DrawingEditControl AddDrawing(DocumentRuntime docRt)
        {
            //var layout = docRt.Document.Layouts.GetByName("左右视口布局");
            //docRt.Document.SetActiveLayout(layout);

            var drawingCtrl = new DrawingEditControl(docRt);
            drawingCtrl.Dock = DockStyle.Fill;
            this.pnlDrawingEditor.Controls.Add(drawingCtrl);
            drawingCtrl.BringToFront();

            drawings.Add(docRt);

            //初始化文档运行时，将输入，渲染与UI对接
            docRt.Initilize(this.commandBar1, drawingCtrl, this.propertyCotrol1);

            //需要等待ViewportRuntime运行后再初始化
            drawingCtrl.InitilizeViewports();

            return drawingCtrl;
        }

        internal void RemoveDrawing(DocumentRuntime docRt)
        {
            var drawingCtrl = docRt.DrawingEditRt.Control as DrawingEditControl;
            this.pnlDocArea.Controls.Remove(drawingCtrl);
            drawings.Remove(docRt);

        }
        internal DocumentRuntime GetLastestDrawing()
        {
            if (this.drawings.Count == 0) return null;
            return this.drawings[this.drawings.Count - 1];
        }



        private void MainMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void Menu_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            UIUtils.ExecuteCommand(e.ClickedItem.Name);
        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            UIUtils.ExecuteCommand(e.ClickedItem.Name);
        }


    }
}
